package com.fd.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      handleRequest(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handleRequest(req, resp);


    }

    private void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("处理post请求");
        //演示从前端获取参数,
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("username = " + username);
        System.out.println("password = " + password);

        resp.getWriter().println("username ="+username);
        resp.getWriter().println("password ="+password);
        System.out.println("this = " + this);

//        从request中获取cookie,默认是数组
//        Cookie[] cookies = req.getCookies();
//        for (Cookie cookie : cookies) {
//            if ("loginUser123".equals(cookie.getName())) {
//                resp.sendRedirect("main.jsp");
//                return;
//            }
//
//        }

        if ( "admin".equals(username) && "admin".equals(password)) {
            //演示在Servlet面的转发,转发的目的地可以是页面,也可以是servlet
//            req.getRequestDispatcher("main.jsp").forward(req,resp);

            //演示通过response来实现重定向重定向
//            Cookie cookie=new Cookie("loginUser123","success");
//            resp.addCookie(cookie);

//            获取session
            HttpSession session = req.getSession();
//          把当前用户放在session中
            session.setAttribute("loginUser","admin");

            resp.sendRedirect("main.jsp");
//            resp.sendRedirect("https://www.baidu.com");
            System.out.println("UserServlet.doPost" );

        }
        resp.setContentType("text/html;charset=UTF-8");
    }
}
